import axios from 'axios'
import qs from 'query-string'
import router from '@/router/index'
// import moment from 'moment'
import store from './store'
import {getStore} from "./storage";
import { Loading } from 'element-ui';

const URL_BASE = process.env.API_URL_BASE;

const hasBody = {
  get: false,
  post: true,
  patch: true,
  put: true,
  delete: true
};

// const deepFormatDates = (obj) => {
//   if (!obj && obj !== 0 && obj !== false) {
//     return obj;
//   }
//
//   switch (obj.constructor) {
//     case Date:
//       return moment(obj).toISOString(true);
//     case Number: case String: case Boolean:
//     return obj;
//     case Array:
//       return obj.map(deepFormatDates);
//     default:
//       return Object.entries(obj).map(([key, value]) => [key, deepFormatDates(value)])
//         .reduce((acc, [key, value]) => Object.assign(acc, {[key]: value}), {});
//   }
// };

const request = function (method, path, params, options) {
  if (!options) options = {silent: false};
  let url = `${URL_BASE}${path}`;
  // params = deepFormatDates(params);
  if (!hasBody[method]) {
    url = `${url}?${qs.stringify(params)}`;
  }

  let currentUser = getStore('user_museum');
  if (currentUser) currentUser = JSON.parse(currentUser);
  let token = currentUser && currentUser.token;

  //loading效果
  let loadingInstance = Loading.service({
      target:'.el-main'
  });

  return axios({
    method: method,
    url: url,
    data: hasBody[method] ? params : undefined,
    headers: {token: token},
    withCredentials: true
  }).catch((error) => {
    if (error.response.status === 401) {
      router.push('/login')
    }
    loadingInstance.close()
    throw error;
  }).then(resp => {
    loadingInstance.close()
    if (resp.data.code === 0) {
      if (method !== 'get' && !options.silent) store.dispatch('putInfo', '操作成功');
      return resp.data.data;
    } else {
      if (!options.silent) store.dispatch('putError', resp.data.message);
      throw resp.data.message;
    }
  })
};

export default Object.keys(hasBody)
  .map(method => [method, (path, params, options) => request(method, path, params, options)])
  .reduce(function (obj, [method, f]) {
    obj[method] = f;
    return obj;
  }, {});
